<!--
 * @Author: yaolunmao
-->
<template>
  <div class="rightNav">
    <a-tabs
      type="card"
      v-model:activeKey="tabsKey"
      class="components-layout-right"
      @change="changeTabs"
    >
      <a-tab-pane key="1" tab="属性">
        <a-collapse
          v-model:activeKey="attributeCollapseKey"
          @click.stop="clickGroup({ groupItem, componentItem })"
          expand-icon-position="right"
        >
          <a-collapse-panel key="1_1" header="属性设置">
            <div class="attribute">
              <a-form labelAlign="right">
                <a-form-item
                  label="类型"
                  v-if="selectSvgInfo.createType || selectSvgInfo.imgType"
                >
                  <p>
                    {{ create_type[selectSvgInfo.createType] }}({{
                      selectSvgInfo.imgType
                    }})
                  </p>
                </a-form-item>
                <a-form-item label="名称">
                  <a-input
                    v-model:value="selectSvgInfo.title"
                    placeholder="请输入组件名称"
                  />
                </a-form-item>
                <a-form-item label="X轴坐标">
                  <a-input-number
                    v-model:value="selectSvgInfo.svgPositionX"
                    :min="0"
                    :max="1920"
                  />
                </a-form-item>
                <a-form-item label="Y轴坐标">
                  <a-input-number
                    v-model:value="selectSvgInfo.svgPositionY"
                    :min="0"
                    :max="1080"
                  />
                </a-form-item>
                <a-form-item label="大小">
                  <a-input-number
                    v-model:value="selectSvgInfo.size"
                    :min="1"
                    :max="3000"
                    step="0.1"
                  />
                </a-form-item>
                <a-form-item label="旋转">
                  <a-input-number
                    v-model:value="selectSvgInfo.angle"
                    :min="0"
                    :max="360"
                  />
                </a-form-item>
                <!-- 自定义属性 -->
                <default-attribute
                  style="padding: 5px 10px"
                  :defaultAttribute="selectSvgInfo.defaultAttr"
                />
              </a-form>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-tab-pane>
      <a-tab-pane key="2" tab="分组">
        <a-spin :spinning="spinning">
          <a-collapse
            v-model:activeKey="groupCollapseKey"
            accordion
            expand-icon-position="right"
          >
            <a-collapse-panel key="2_1" header="事件分组">
              <group-components
                :popGroupIndex="0"
                :popComponentIndex="0"
                :groupLists="groupLists"
                :svgInfo="svgInfo"
                :selectSvgInfo="selectSvgInfo"
                :fatherGroupItem="groupList[0]"
                @addGroupMethod="addGroupMethod"
                @clickGroup="clickGroup"
                @handleMenu="handleMenu"
                @inputBlur="inputBlur"
              />
              <div class="button" v-if="groupLists[0]?.componentsList">
                <a-button type="primary" @click.stop="submitGroup"
                  >保存</a-button
                >
              </div>
            </a-collapse-panel>
          </a-collapse>
        </a-spin>
      </a-tab-pane>
      <a-tab-pane key="3" tab="数据">
        <a-form :model="selectSvgInfo">
          <a-form-item
            style="width: 260px"
            :labelCol="{ span: 6 }"
            colon
            label="类型"
          >
            <a-select
              placeholder="请选择关联的类型"
              allowClear
              v-model:value="selectSvgInfo.componentDataSource"
              style="width: 180px"
            >
              <a-select-option
                v-for="item in component_data_source"
                :key="item"
                :value="item.value"
                >{{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            style="width: 260px"
            colon
            :labelCol="{ span: 6 }"
            label="数值KEY"
          >
            <div class="formItem">
              <a-input
                placeholder="请选择关联数值KEY"
                v-model:value="selectSvgInfo.dataKeyName"
                style="width: 180px"
                :disabled="true"
              >
                <template #suffix v-if="selectSvgInfo.dataKeyName">
                  <close-circle-outlined
                    @click="deleteValue('dataKey')"
                    style="color: rgba(0, 0, 0, 0.45); cursor: pointer"
                  />
                </template>
              </a-input>
              <!-- <a-cascader
                style="width: 180px"
                :field-names="{ label: 'typeName', value: 'id' }"
                allowClear
                v-model:value="selectSvgInfo.dataKeyId"
                :load-data="loadData"
                :options="valueOptions"
                placeholder="请选择关联数值KEY"
              /> -->
              <switcher-filled
                @click="openListModel('数值KEY')"
                style="
                  font-size: 25px;
                  margin-left: 10px;
                  color: rgb(24, 144, 255);
                "
              />
            </div>
          </a-form-item>
          <a-form-item
            style="width: 260px"
            colon
            :labelCol="{ span: 6 }"
            label="状态KEY"
          >
            <div class="formItem">
              <!-- <a-cascader
                style="width: 180px"
                :field-names="{ label: 'typeName', value: 'id' }"
                allowClear
                v-model:value="selectSvgInfo.stateKeyId"
                :load-data="loadData"
                :options="valueOptions"
                placeholder="请选择关联状态KEY"
                change-on-select
              /> -->
              <a-input
                placeholder="请选择关联状态KEY"
                v-model:value="selectSvgInfo.stateKeyName"
                style="width: 180px"
                :disabled="true"
              >
                <template #suffix v-if="selectSvgInfo.stateKeyName">
                  <close-circle-outlined
                    @click="deleteValue('stateKey')"
                    style="color: rgba(0, 0, 0, 0.45); cursor: pointer"
                  />
                </template>
              </a-input>
              <switcher-filled
                @click="openListModel('状态KEY')"
                style="
                  font-size: 25px;
                  margin-left: 10px;
                  color: rgb(24, 144, 255);
                "
              />
            </div>
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script>
import { message } from 'ant-design-vue';
import defaultAttribute from './defaultAttribute.vue';
import GroupComponents from '@/components/GroupComponents.vue';
import { SwitcherFilled, CloseCircleOutlined } from '@ant-design/icons-vue';
import { toParse, aimToArr, toStringify } from '@/util';
import {
  addGroup,
  listEventGroup,
  generalDict,
  keyRuleDefineLazyLoad,
} from '@/network/api';
export default {
  props: ['svgInfo', 'svgLists', 'templateId'],
  data() {
    return {
      component_data_source: {}, //操作类型
      create_type: {
        draggable: '拖拽式',
        draw: '绘制式',
      },
      spinning: false,
      tabsKey: '1',
      groupList: [],
      groupLists: [],
      attributeCollapseKey: ['1_1'],
      groupCollapseKey: ['2_1'],
      //基础分组
      baseGroups: {
        //-------前端数据--------------------//
        isAddStatus: true, //当前组是否可增加组件 || 子组状态
        collpaseStatus: true, //当前组的收缩状态
        editStatus: false, //分组标题编辑状态
        activeTabsKey: 'openValve', //当前组的activeKey
        menusConfig: [
          {
            name: '添加下级分组',
            type: 'group',
          },
          {
            name: '移除分组',
            type: 'group',
          },
        ],
        //---------------------------------//
      },
      currentSelectSvg: {},
      valueOptions: [],
      loadData: null,
      dataFormKey: {
        typeKey: null,
        valueKey: null,
        statusKey: null,
      },
    };
  },
  mounted() {
    this.getDict();
    // 监听父页面向子页面的传参
    window.addEventListener('message', (e) => {
      this.iframeEvent(e.data);
    });
  },
  computed: {
    selectSvgInfo() {
      return this.svgInfo;
    },
  },
  watch: {
    'selectSvgInfo.tableRowCount': function (newVal) {
      this.$emit(
        'setTableAttr',
        this.selectSvgInfo.componentDataId,
        newVal,
        this.selectSvgInfo.tableColCount
      );
    },
    'selectSvgInfo.tableColCount': function (newVal) {
      this.$emit(
        'setTableAttr',
        this.selectSvgInfo.componentDataId,
        this.selectSvgInfo.tableRowCount,
        newVal
      );
    },
    svgInfo: {
      deep: true,
      immediate: true,
      handler(val) {
        val.type == 'WaterPipeValveSvg'
          ? this.recursionFindActiveGroup(this.groupLists)
          : '';
        JSON.stringify(val) != '{}' ? this.addComponent(val) : '';
      },
    },
  },
  methods: {
    deleteValue(val) {
      switch (val) {
        case 'dataKey':
          this.selectSvgInfo.dataKeyName = '';
          this.selectSvgInfo.dataKeyId = '';
          break;
        case 'stateKey':
          this.selectSvgInfo.stateKeyName = '';
          this.selectSvgInfo.stateKeyId = '';
          break;
        default: {
        }
      }
    },
    iframeEvent(val) {
      switch (val.data.type.title) {
        case '数值KEY':
          this.selectSvgInfo.dataKeyName = val.data.data.keyName;
          this.selectSvgInfo.dataKeyId = val.data.data.keyValue;
          break;
        case '状态KEY':
          this.selectSvgInfo.stateKeyName = val.data.data.keyName;
          this.selectSvgInfo.stateKeyId = val.data.data.keyValue;
          break;
      }
    },
    openListModel(val) {
      window.parent.postMessage({ type: 'openModel', data: val }, '*');
    },
    getKeyRuleDefineLazyLoad(targetOption = { id: '' }, selectedOptions) {
      targetOption.loading = true;
      let params = { id: targetOption.id };
      //不要问第4次才加id进行组合查询，要问就问后端
      selectedOptions?.length >= 4
        ? Object.assign(params, {
            typeId: selectedOptions[0]?.id,
            registerId: selectedOptions[1]?.id,
            registerSubtypeId: selectedOptions[2]?.id,
            crewId: selectedOptions[3]?.id,
            childId: selectedOptions[4]?.id,
          })
        : '';

      this.$httpRequest(keyRuleDefineLazyLoad, params)
        .then((res) => {
          res.data.forEach((item) => {
            item.isLeaf = !item.isSubordinate;
          });
          if (targetOption.id) {
            targetOption.children = res.data;
            this.valueOptions = [...this.valueOptions];
          } else {
            this.valueOptions = res.data;
          }
          targetOption.loading = false;
        })
        .catch(() => {
          targetOption.loading = false;
        });
    },
    //add group
    addGroupMethod(list) {
      // 开关类组件才能创建相关组(改变增加组按钮的状态)
      switch (this.svgInfo.type) {
        case 'WaterPipeValveSvg':
          list.push(
            JSON.parse(
              JSON.stringify(
                Object.assign(this.baseGroups, {
                  componentsList: [], //组件
                  groupLists: [], //子分组
                  type: this.svgInfo.type,
                  componentDataId: this.svgInfo.componentDataId,
                  title: this.svgInfo.title,
                })
              )
            )
          );
          this.chengeAddGroupButtonStatus(this.svgInfo, true, list[0]);
          break;
        default:
          message.warning('创建相关组,请选择开关类组件哦~');
          break;
      }
    },
    //点击分组 || 点击分组组件
    clickGroup(clickItem) {
      if (
        clickItem?.componentItem?.componentDataId ==
        this.svgInfo.componentDataId
      )
        return;
      let resetActive = (list) => {
        list.forEach((item) => {
          clickItem.componentItem ? (item.isAddStatus = true) : '';
          item.isAddStatus =
            clickItem.groupItem.componentDataId == item.componentDataId
              ? true
              : false;
          item.groupLists ? resetActive(item.groupLists) : '';
        });
      };
      //点击子组件，重置其他组状态
      resetActive(this.groupLists);
      //子组件互联状态
      clickItem?.componentItem
        ? this.$emit('changeSvgInfo', clickItem.componentItem)
        : '';
    },
    //click menus
    handleMenu(val) {
      switch (val.key) {
        case 0:
          //当前组的组件不能被重复创建(同级 || 下级)
          val.value1.componentDataId != this.svgInfo.componentDataId
            ? this.addGroupMethod(val.value1.groupLists)
            : '';
          break;
        case 1:
          val.type == 'group'
            ? this.chengeAddGroupButtonStatus(
                this.svgInfo,
                false,
                val.value1[0]
              )
            : '';
          val.value1.splice(val.value2, 1);
          break;
      }
    },
    getDict() {
      this.$httpRequest(generalDict, {
        dictType: 'component_data_source',
      }).then((res) => {
        this.component_data_source = aimToArr(res);
      });
    },
    //input blur event
    inputBlur(val) {
      val.editStatus = !val.editStatus;
      !val.title ? (val.title = this.selectSvgInfo.title) : '';
    },
    //保存分组
    submitGroup() {
      if (this.templateId) {
        //全部自定义属性改成string
        toStringify(this.groupLists);
        this.$httpRequest(
          addGroup,
          {
            addEventGroupDetailForm: this.groupLists,
            waterTemplateId: this.templateId,
          },
          'post'
        ).then(() => {
          message.success('保存成功~');
          toParse(this.groupLists);
        });
      } else {
        message.warning('请保存当前模板哦~');
      }
    },
    //递归查找active group
    recursionFindActiveGroup(list) {
      list.length
        ? list.forEach((item) => {
            if (item.componentDataId == this.svgInfo.componentDataId) {
              item.isAddStatus = true;
              item.groupLists
                ? this.recursionFindActiveGroup(item.groupLists)
                : '';
            } else {
              item.isAddStatus = false;
              item.groupLists
                ? this.recursionFindActiveGroup(item.groupLists)
                : '';
            }
          })
        : '';
    },
    countComponent(list) {
      let count = 0;
      let countNumber = (list) => {
        list
          ? list.forEach((item) => {
              count += 1;
              item.componentsList ? (count += item.componentsList.length) : '';
              if (item.groupList.length) {
                countNumber(item.groupList);
              }
              item.groupComponentsCount = count;
            })
          : '';
      };
      countNumber(list);
      return count;
    },
    //show or hide add group button
    chengeAddGroupButtonStatus(obj, val, list) {
      obj.hideAddGroup = val;
      list.hideAddGroup = val;
      let deleteComponentsArr = [];
      deleteComponentsArr.push({
        componentDataId: list.componentDataId,
        hideAddGroup: list.hideAddGroup,
      });
      let resetAddGroupStatus = (list) => {
        list.forEach((item) => {
          item.hideAddGroup = val;
          //取出当前子分组的状态,改变源数据的状态（组件是否可增加分组）
          deleteComponentsArr.push({
            componentDataId: item.componentDataId,
            hideAddGroup: item.hideAddGroup,
          });
          item.groupLists ? resetAddGroupStatus(item.groupLists) : '';
        });
      };
      list.groupLists ? resetAddGroupStatus(list.groupLists) : '';
      deleteComponentsArr
        ? this.$emit('changeSvgComponentsStatus', deleteComponentsArr)
        : '';
    },
    //active group push components
    addComponent(val) {
      let addModel;
      switch (val.type) {
        case 'WaterPipeValveSvg':
          break;
        default:
          addModel = (list) => {
            //逻辑1 => 当前组件只能存在一个分组里面(子分组和同级分组同时存在时，有点小问题)
            // list
            //   ? list.forEach((item) => {
            //       if (
            //         item.isAddStatus &&
            //         item.componentDataId != val.componentDataId
            //       ) {
            //         console.log(this.searchGroupListsSurviveCompoennt(val));
            //         if (!this.searchGroupListsSurviveCompoennt(val)) {
            //           item.componentsList.push({
            //             componentDataId: val.componentDataId,
            //             title: val.title,

            //             collpaseStatus: false, //组件属性收缩状态
            //             editStatus: false, //分组标题编辑状态
            //             menusConfig: [
            //               {
            //                 name: '移除组件',
            //                 type: 'group',
            //               },
            //             ],
            //             defaultAttr: {},
            //           });
            //           console.log(item.componentsList);
            //         }
            //       } else {
            //         item.groupLists ? addModel(item.groupLists) : '';
            //       }
            //     })

            //   : '';

            //逻辑2 => 组件可以同时存在不同的组(子组、同级组等等)
            list
              ? list.forEach((item) => {
                  if (
                    item.isAddStatus &&
                    !item.componentsList.filter((componentItem) => {
                      return (
                        componentItem.componentDataId == val.componentDataId
                      );
                    }).length
                  ) {
                    item.componentsList.push({
                      componentDataId: val.componentDataId,
                      title: val.title,
                      //阀门开启 && 关闭状态
                      openValve: JSON.parse(JSON.stringify(val.defaultAttr)),
                      closeValve: JSON.parse(JSON.stringify(val.defaultAttr)),

                      collpaseStatus: false, //组件属性收缩状态
                      editStatus: false, //分组标题编辑状态
                      menusConfig: [
                        {
                          name: '移除组件',
                          type: 'group',
                        },
                      ],
                      type: val.type,
                    });
                  }
                  item.groupLists ? addModel(item.groupLists) : '';
                })
              : '';
          };
          addModel(this.groupLists);
          break;
      }
    },
    //查询当前分组是否存在当前组件
    searchGroupListsSurviveCompoennt(component) {
      let flage;
      let searchComponents = (list) => {
        try {
          list.forEach((groupItem) => {
            if (groupItem.componentDataId == component.componentDataId) {
              throw new Error(true);
            } else {
              flage = false;
            }
            groupItem.componentsList.length
              ? groupItem.componentsList.forEach((componentItem) => {
                  if (
                    componentItem.componentDataId == component.componentDataId
                  ) {
                    throw new Error(true);
                  } else {
                    flage = false;
                  }
                })
              : '';
            groupItem.groupLists.length
              ? searchComponents(groupItem.groupLists)
              : '';
          });
        } catch (err) {
          flage = err.message;
        }
      };
      searchComponents(this.groupLists);
      return flage;
    },
    //查询分组
    getTemplateGroup(id) {
      this.spinning = true;
      this.$httpRequest(listEventGroup, { waterTemplateId: id })
        .then((res) => {
          this.spinning = false;
          if (res.data) {
            let addAttribute = (list) => {
              list.forEach((item) => {
                Object.assign(item, this.baseGroups);
                item.groupLists
                  ? addAttribute(item.groupLists)
                  : (item.groupLists = []);
              });
            };
            res.data ? addAttribute(res.data) : '';
            res.data ? toParse(res.data) : '';
            //回显
            this.groupLists = res.data;
            this.recursionFindActiveGroup(this.groupLists);
          }
        })
        .catch(() => {
          this.spinning = false;
        });
    },
    changeTabs(activeKey) {
      if (this.templateId) {
        activeKey == 2 ? this.getTemplateGroup(this.templateId) : '';
      }
    },
  },
  components: {
    GroupComponents,
    SwitcherFilled,
    CloseCircleOutlined,
    defaultAttribute,
  },
};
</script>
<style scoped lang="less">
::-webkit-scrollbar {
  width: 6px;
  height: 5px;
}
::-webkit-scrollbar-track {
  border-radius: 10px;
  background-color: #f2f2f2;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: #9e9e9e;
}
.components-layout-right {
  .ant-tabs-bar {
    margin-bottom: 0 !important;
  }

  .ant-form-item-label {
    width: 100px !important;
    flex-shrink: 0;
  }

  .ant-input-number,
  input {
    width: 160px;
    border-radius: 4px;
    border-color: #ddd;
  }

  .ant-form-item-control {
    line-height: 24px !important;

    p {
      margin-bottom: 0 !important;
    }
  }

  .ant-form-item {
    display: flex;
    align-items: center;
    flex-flow: nowrap;
    position: relative;
    margin-bottom: 0;
    padding: 5px 10px;

    &:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 15px;
      right: 15px;
      bottom: 0;
      height: 1px;
    }

    &:last-child::after {
      content: unset;
    }
  }
}

/deep/ .vc-color-wrap {
  width: 70%;
}

.formItem {
  display: flex;
}

.attribute {
  overflow: auto;
  height: 584px;
}

.btn-sure {
  width: 260px;
  margin: 20px;
}

.bg-code {
  background: #444;
  color: #fff;
  width: calc(100% - 20px);
  margin: 20px 10px;
  border-radius: 4px;
  padding: 10px;
}

.rightNav {
  right: 0;
  top: 0;
  bottom: 0;
  min-width: unset !important;
  max-width: unset !important;
  width: 300px !important;
  z-index: 1;
  overflow: auto;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
  -ms-user-select: none;
}

.button {
  margin: 10px;
  text-align: center;
}

/deep/ .ant-collapse-content > .ant-collapse-content-box {
  padding: 0px !important;
}
</style>
